<template>
  <div>
  <div class="white-bar">
    <div class="flex-spacer"></div>
      <div class="timer">
             面试时长：{{ formattedTime }}
      </div>
     <button class="end-button" @click="endInterview" title="提前结束不会生成报告和记录">
        <i class="icon-ym icon-ym-generator-radio">提前结束</i>
      </button>
  </div>
  <div class="interview-analysis-container">
    <!-- 左侧区域：视频 + 题目交互 -->
    <div class="left-section">
      <div class="video-wrap">
          <ai ref="aiComponent" :interviewer="interviewerFromStore"/>
      </div>
      <div class="qa-interact">
        <div class="question-box">
          <p class="question-label">面试官</p>
          <p class="question-content">{{ interviewQuestion }}</p>
        </div>
      </div>
      <div class="btn-group1">
        <interview-question-generator
          ref="questionGenerator"
          :model-domain="modelDomain"
          :app-id="appId"
          :api-key="modelAPIKey"
          :api-secret="modelAPISecret"
          :model-http-url="modelHttpUrl"
        />
      </div>
    </div>

    <!-- 中间区域：分析模块 -->
    <div class="middle-section">
      <div class="top-analysis">
        <div class="analysis-card voice-analysis">
          <h3 class="card-title">语音情感分析</h3>
          <div class="emotion-chart">
          </div>
          <p v-if="analysisResult" class="emotion-score">情感指数：{{ (analysisResult.sentiment[0].score * 100).toFixed(1) }}/100</p>
          <p v-if="analysisResult" class="emotion-tip">{{ analysisResult.logic.flag ? '⚠️ ' + analysisResult.logic.message : '✅ ' + (analysisResult.logic.message || '未检测到明显逻辑矛盾。') }}</p>
          <div  ref="scoreChart" style="width: 100%; height: 140px; margin-top:10px;"></div>
        </div>

        <div class="analysis-card expression-analysis">
          <h3 class="card-title">微表情分析</h3>
          <div class="expression-info">
            <div class="expression-icon">{{ expressionIcon }}</div>
            <div class="expression-text">
              <p>当前表情：{{ currentEmotion }}</p>
            </div>
          </div>
          <div  ref="chart" style="width: 100%; height: 90px; margin-top: 28px;"></div>
        </div>
      </div>

      <div class="answer-comparison-card">
        <div class="answer-title-group">
          <h3 class="ai-answer-title">智能回答</h3>
        </div>
        <div class="answer-content-group">
          <!-- 智能回答 - 上侧 -->
          <div class="ai-answer answer-panel">
            <div class="answer-scroll-container">
              <div v-if="aiAnswerContent && aiAnswerContent !== '点击获取智能回答按钮生成回答建议'">
                <p v-html="aiAnswerContent" class="answer-content1"></p>
              </div>
              <div v-else-if="aiAnswerContent === '点击获取智能回答按钮生成回答建议'">
                <div class="default-answer提示">
                  {{ aiAnswerContent }}
                </div>
              </div>
              <div v-else class="no-answer提示">
                <div class="no-answer-icon">🤖</div>
                <div class="no-answer-text">暂无智能回答</div>
              </div>
            </div>
          </div>
        </div>
      </div>
       <div class="answer-box">
          <p class="answer-content2"  v-html="formattedResult"></p>
          <div class="btn-group">
            <button
              class="next-btn beautify-btn"
              @click="getAiAnswer"
              :disabled="answerCount == maxAnswerCount"
            >
              <i class="ym-custom ym-custom-robot"></i>
              智能回答
            </button>
            <button class="analysis-btn1 beautify-btn" @click="toggleAnalysis"><i class="el-icon-data-analysis"></i> 查看分析</button>
            <button
              class="analysis-btn beautify-btn"
              @click="toggleRecording"
              :disabled="answerCount == maxAnswerCount"
            >
              <i :class="isRecording ? 'el-icon-turn-off-microphone' : 'el-icon-microphone'"></i>
              {{ buttonText }}
            </button>
            <button
              class="next-btn1 beautify-btn"
              @click="handleNextQuestion"
              :disabled="modelLoading || analysisLoading">
              <i class="el-icon-s-promotion"></i>
              {{ answerCount == maxAnswerCount ? '结束' : '回答完毕' }}
            </button>
          </div>
        </div>
    </div>

    <!-- 右侧区域：历史回答（独立滚动） -->
    <div class="right-section history-section">
      <div>
        <!-- <button class="analysis-btn" @click="toggleRun">{{ running ? '关闭摄像头' : '开启摄像头' }}</button> -->
        <div class="camera-area" style="position:relative;width:300px;height:210px;">
          <video
            ref="video"
            class="camera-video"
            autoplay
            playsinline
            :class="{'video-inactive': !running}"
          ></video>
          <button
            class="camera-toggle-btn"
            @click="toggleRun"
            title="开启/关闭摄像头"
            :class="{ 'always-show': !running }"
          >
            <i :class="running ? 'ym-custom ym-custom-camera' : 'ym-custom ym-custom-camera-off'"></i>
          </button>
        </div>
      </div>
      <div class="history-header">
        <h3 class="history-title">回答记录</h3>
        <div class="history-filter">
          <!-- 筛选按钮 -->
          <button class="filter-btn" @click="filterHistory('all')">全部</button>
          <button class="filter-btn" @click="filterHistory('high')">高分</button>
          <button class="filter-btn" @click="filterHistory('low')">低分</button>
        </div>
      </div>

      <div class="history-scroll-container">
        <div v-if="filteredHistoryData.length === 0" class="no-history-record">
        <div class="no-record-icon">📝</div>
        <div class="no-record-text">当前暂无回答记录</div>
      </div>
      <div class="history-list" v-else>
        <div
          v-for="(item, index) in filteredHistoryData"
          :key="index"
          class="history-item"
          @click="viewHistoryDetail(item)"
          :class="{ 'high-score': item.score >= 8, 'low-score': item.score < 8 }"
        >
          <div class="history-question">
            <p class="history-q-title">问题</p>
            <p class="history-q-content">{{ item.question }}</p>
          </div>
          <div class="history-meta">
            <span class="history-time">{{ item.time }}</span>
            <span class="history-score">得分: {{ item.score }}/10</span>
          </div>
        </div>
      </div>
    </div>

     <!-- 历史记录详情模态框 -->
    <div v-if="showHistoryModal" class="history-modal">
      <div class="modal-mask" @click="closeHistoryModal"></div>
      <div class="history-detail-panel">
        <div class="panel-header">
          <h3 class="panel-title">回答详情</h3>
          <button class="close-btn" @click="closeHistoryModal">×</button>
        </div>
        <div class="detail-content">
          <div class="detail-section">
            <h4 class="section-title">面试官问题</h4>
            <div class="question-display">{{ historyDetail.question }}</div>
          </div>

          <div class="detail-section">
            <h4 class="section-title">我的回答</h4>
            <div class="answer-display" v-html="historyDetail.answer"></div>
          </div>

          <div class="detail-section">
            <h4 class="section-title">回答分析</h4>
            <div class="analysis-display">
              <div v-if="historyDetail.analysis.advantage" class="analysis-subsection">
                <h5 class="subsection-title">优势分析</h5>
                <div v-html="historyDetail.analysis.advantage"></div>
              </div>
              <div v-if="historyDetail.analysis.disadvantage" class="analysis-subsection">
                <h5 class="subsection-title">改进建议</h5>
                <div v-html="historyDetail.analysis.disadvantage"></div>
              </div>
              <div v-if="!historyDetail.analysis.advantage && !historyDetail.analysis.disadvantage" class="no-analysis">
                暂无分析结果
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4 class="section-title">回答信息</h4>
            <div class="info-display">
              <p><span class="info-label">回答时间:</span> {{ historyDetail.time }}</p>
              <p><span class="info-label">得分:</span> {{ historyDetail.score }}/10</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="showAnalysis" class="analysis-modal">
      <div class="modal-mask" @click="toggleAnalysis"></div>
      <div class="analysis-panel">
        <div class="panel-header">
        <h3 class="panel-title">回答分析</h3>
        <div>
          <button class="close-btn" @click="toggleAnalysis">×</button>
        </div>
      </div>
        <div class="analysis-content">
          <div class="analysis-left">
            <h4 class="section-title">我的回答</h4>
            <div class="answer-display" v-html="formattedResult || globalAnswer || myAnswerContent"></div>
          </div>
          <div class="analysis-right">
          <h4 class="section-title">分析结果</h4>

          <div class="analysis-type-toggle">
              <button
                class="analysis-type-btn"
                :class="{ 'active': currentAnalysisType === 'advantage' }"
                @click="switchAnalysisType('advantage')"
              >
                优势分析
              </button>
              <button
                class="analysis-type-btn"
                :class="{ 'active': currentAnalysisType === 'disadvantage' }"
                @click="switchAnalysisType('disadvantage')"
              >
                改进建议
              </button>
              <button
                class="reanalyze-btn"
                @click="reAnalyzeAnswer"
              >
                重新分析
              </button>
            </div>
            <div class="model-analysis-result">
              <h5 v-if="currentAnalysisType === 'advantage'" style="color: green; margin-top: 0;">优势分析</h5>
              <h5 v-if="currentAnalysisType === 'disadvantage'" style="color: red; margin-top: 0;">改进建议</h5>

              <div v-if="modelAnalysisError" class="analysis-error">{{ modelAnalysisErrorMsg }}</div>

              <div v-if="!modelAnalysisError" class="result-container">
                <div v-if="streamingAnalysisText" v-html="formatAnalysisResult(streamingAnalysisText)"></div>
                <div v-else v-html="currentAnalysisType === 'advantage' ? formattedAdvantageText : formattedDisadvantageText"></div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>

  </div>
  </div>
 </div>
</template>

<script>
import RecorderManager from 'recorder-manager';
import CryptoJS from 'crypto-js';
import ai from '@/views/Ada/views/avatardemo.vue'
import InterviewQuestionGenerator from './style/style.vue';
import { mapGetters, mapMutations, mapActions } from 'vuex';
import request from '@/utils/request'
import roleOptions from '@/assets/position/role-options.js'

export default {
  components:{ai,InterviewQuestionGenerator},
  name: 'InterviewAnalysis',
  data() {
    return {
      isRecording: false,
      currentScene: 'default', // 当前使用的场景
      sceneOrder: 0, // 场景切换顺序索引
      answerCount: 0, // 当前回答次数
      maxAnswerCount: 3, // 最大回答次数
      availableScenarios: [],
      currentScenario: 'default',
      userAnswer: '', // 用户回答，可根据实际交互填充
      currentExpression: '平静', // 当前表情
      dura: '',
      myAnswerContent: ``,
      aiAnswerContent: ``,
      steamingContent:'',
      historyFilter: 'all',
      showAnalysis: false,
      totalAnalysisRes: '',
      evaluationLoading: false,
      evaluationContent: '',
      finalEvaluation: null,
      // 用于缓存大模型分析结果
      analysisCache: {
        advantage: null,
        disadvantage: null
      },
      streamingAnalysisText: '',
      // 标记是否已加载过优点和缺点
      hasLoadedAdvantage: false,
      hasLoadedDisadvantage: false,
      // 当前显示的分析类型
      currentAnalysisType: 'advantage',
      modelAnalysisErrorMsg: '',
      //回答记录
      historyFilter: 'all',
      showHistoryModal: false,
      historyDetail: {
        question: '',
        answer: '',
        analysis: {
          advantage: '',
          disadvantage: ''
        },
        time: '',
        score: 0
      },
      // 模拟评分逻辑的基准分
      baseScore: 70,
      // 历史记录数据结构增强
      historyData: [],
      APPID: '95dbb1b4',
      API_KEY: '9e6fd955d27607479d5e0a6dea7b0a7e',
      //大模型相关参数
      modelAPIKey: '11de41665ee9edf55435d97d46f0ea56', // 大模型API Key
      modelAPISecret: 'MmE5NWI0N2E1MjJjODg0ODE0ZjRiZDU4', // 大模型API Secret
      modelHttpUrl: new URL("https://spark-api.xf-yun.com/v3.5/chat"),
      modelDomain: 'generalv3.5',
      modelWS: null,
      modelLoading: false,

      scoringLoading: false, // 评分加载状态
      scoringError: false, // 评分错误标志
      scoringErrorMessage: '', // 评分错误信息

      //智能分析
      advantageText: '',
      disadvantageText: '',
      formattedAdvantageText: '',
      formattedDisadvantageText: '',
      analysisLoading: false,
      modelAnalysisError: false,
      appId: '95dbb1b4',
      apiSecret: 'MmE5NWI0N2E1MjJjODg0ODE0ZjRiZDU4',
      apiKey: '11de41665ee9edf55435d97d46f0ea56',
      analysisModelWS: null,

      //新增大模型相关参数
      nextQuestionLoading: false,
      nextQuestionContent: '',
      isStreaming: false, // 标记是否正在接收流式数据
      modelResponseBuffer: '', // 优化的响应缓冲区

      recorder: null,
      asrWebSocket: null,
      analysisWebSocket: null,
      analysisWSConnected: false,
      recognitionResult: '',
      globalAnswer:'',
      tempResult: '',
      isRecording: false,
      isLoading: false,
      connectionStatus: 'CLOSED',
      analysisResult: null,
      currentEmotion: '',
      pendingEmotion: '',
      stableCount: 0,
      stableThreshold: 3,
      lastEmotion: '',
      startTime: null,
      videoFrame: null, // 摄像头视频帧
      duration: 0,
      running: false,
      socket: null,
      videoStream: null,  // 新增，存摄像头流
      labelMap: {
        angry: '严肃',
        disgust: '厌恶',
        scared: '害怕',
        happy: '高兴',
        sad: '伤心',
        surprised: '惊讶',
        neutral: '平静'
      },
      scoreHistory: [],
      scoreTimer: null,
      scoreChartInstance: null,
      timer: null,
      emotionHistory: [],
      chart: null,
      //这是存最后生成报告的完整记录的，勿删谢谢合作！！！！！
        recordDataForm: {
          inid : '',
          date : '',
          record : '',
          vedio : '',
          voice : '',
      },
      //面试记录
      interviewRecordForm: {
                            inid : '',
                            scene : '',
                            intype : '',
                            style : '',
                            todate : "",
                            type : '',
                            userid : "",
                            time : '',
            },

    }
  },
  computed: {
    formattedTime() {
      // 计算小时、分钟和秒
      const hours = Math.floor(this.dura / 3600); // 计算小时
      const minutes = Math.floor((this.dura % 3600) / 60); // 计算分钟
      const seconds = this.dura % 60; // 计算秒数

      // 格式化显示
      let formatted = '';
      if (hours > 0) {
        formatted += `${hours}小时`;
      }
      if (minutes > 0 || hours > 0) {
        formatted += `${minutes}分钟`;
      }
      formatted += `${seconds}秒`;

      return formatted;
    },
    interviewCount() {
    return this.$store.getters['scene/getInterviewCount'];
    },
    interviewerFromStore() {
      return this.$store.getters['scene/getInterviewer'];
    },
    // 从Vuex获取选中的场景列表和当前场景
    selectedScenes() {
      return this.$store.getters['scene/getSelectedScenes'];
    },
      ...mapGetters('userSelection', {
      getTechField: 'getTechField',
      getPosition: 'getPosition',
      getLanguages: 'getLanguages'
    }),

    currentSceneFromStore() {
      return this.$store.getters['scene/getCurrentScene'];
    },
    hasMultipleScenes() {
      return this.selectedScenes.length > 1;
    },
    filteredHistoryData() {
      if (this.historyFilter === 'all') {
        return this.historyData;
      } else if (this.historyFilter === 'high') {
        return this.historyData.filter(item => item.score >= 80);
      } else if (this.historyFilter === 'low') {
        return this.historyData.filter(item => item.score < 80);
      }
      return this.historyData;
    },
    ...mapGetters('answer', {
      getGlobalAnswer: 'getInterviewAnswer'
    }),
    ...mapGetters('question',['getInterviewQuestion']),
    interviewQuestion(){
      return this.getInterviewQuestion;

    },
    buttonText() {
      if (this.connectionStatus === 'CONNECTING') return '';
      if (this.connectionStatus === 'OPEN') return '结束';
      return '开始';
    },
    formattedResult() {
      return (this.recognitionResult || '') + (this.tempResult ? `<span class="temp">${this.tempResult}</span>` : '');
    },
    expressionIcon() {
      const map = {
        '严肃': '😠',
        '开心': '😄',
        '悲伤': '😢',
        '中性': '😐',
        '厌恶': '🤢',
        '惊讶': '😲',
        '恐惧': '😨',
        'unknown': '❓'
      }
      return map[this.currentEmotion] || '❓'
    },
  },
  watch:{
    getGlobalAnswer(newVal){
      this.globalAnswer=newVal;
    },
    //监听问题变化
    interviewQuestion() {
      this.aiAnswerContent = '点击"获取智能回答"按钮生成回答建议';
    },
  },
  mounted() {
    console.log('当前最大面试次数:', this.interviewCount);
    this.maxAnswerCount=this.interviewCount;
    // 确保虚拟人组件已接收面试官信息
    if (this.$refs.aiComponent && this.interviewerFromStore) {
      console.log('传递面试官配置到虚拟人组件:', this.interviewerFromStore);
      this.$refs.aiComponent.startAll()
      this.$refs.aiComponent.startVirtualHuman()
    }
    //从Vuex获取选中的场景
    const selectedScenes = this.$store.getters['scene/getSelectedScenes'];
    const currentScene = this.$store.getters['scene/getCurrentScene'];
    console.log('从Vuex获取的选中场景:', selectedScenes);
    console.log('当前场景:', currentScene);
    console.log('岗位',this.getPosition);
    // 初始化当前场景
    this.initCurrentScene();
    //console.log('可用场景:', this.availableScenarios);
    this.initRecorder();
    this.initAnalysisWebSocket();
    this.getModelDomain();
    // 检查 ai 组件是否存在
    if (this.$refs.aiComponent) {
      console.log('AI组件已挂载');
    } else {
      console.warn('AI组件未挂载，请检查模板引用');
    }
    this.$nextTick(() => {
      // 确保 DOM 已渲染
        this.updateScoreChart();
        this.drawChart();
    });
  },
  created() {
    // 初始化计时器
    this.startTime = Date.now();
    this.dura = 0;

    // 设置每秒更新一次的计时器
    this.timer = setInterval(() => {
      this.dura = Math.floor((Date.now() - this.startTime) / 1000); // 计算秒数
    }, 1000);
  },
  beforeDestroy() {
    this.disconnect();
    this.cleanupAnalysisWS();
    this.closeModelWS();// 销毁前关闭大模型WebSocket
    this.closeAnalysisModelWS();
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    // 初始化当前场景
    initCurrentScene() {
      if (this.selectedScenes.length > 0) {
        this.currentScene = this.selectedScenes[0];
      } else {
        this.currentScene = 'default'; // 默认场景
      }
      console.log('初始化场景:', this.currentScene);
    },
    // 生成下一个问题时应用当前场景
    async generateNextQuestion() {
      const currentQuestion = this.interviewQuestion;
      const userAnswer = this.recognitionResult || this.globalAnswer || this.myAnswerContent;

      if (!currentQuestion || !userAnswer) {
        this.nextQuestionContent = '生成失败：缺少问题或回答内容';
        this.nextQuestionLoading = false;
        return;
      }

      // 调用问题生成组件时指定当前场景
      this.$refs.questionGenerator.generateQuestion(
        currentQuestion,
        userAnswer,
        this.currentScene
      ).then(newQuestion => {
        this.nextQuestionContent = newQuestion;
        this.updateQuestion(newQuestion);
        this.invokeAvatarComponent(newQuestion);
      }).catch(error => {
        console.error('生成问题失败:', error);
        this.nextQuestionContent = `生成失败: ${error.message || '未知错误'}`;
      });
    },
    // 切换到下一个场景
    switchToNextScene() {
      if (!this.hasMultipleScenes) return;

      this.sceneOrder = (this.sceneOrder + 1) % this.selectedScenes.length;
      this.currentScene = this.selectedScenes[this.sceneOrder];
      this.$store.dispatch('scene/changeCurrentScene', this.currentScene);
      console.log('切换到场景:', this.currentScene);
    },
    // 获取所有历史记录
    getAllHistories() {
      const histories = this.$store.getters['history/getAllInterviewHistories'];
      console.log('所有历史记录:', histories);
      return histories;
    },
    endInterview(){
       this.$router.push({ path: '/homePage' });
    },
    // 获取最新历史记录
    getLatestHistory() {
      const latest = this.$store.getters['history/getLatestInterviewHistory'];
      console.log('最新历史记录:', latest);
      return latest;
    },

    // 按日期获取历史记录
    getHistoriesByDate(date = new Date()) {
      const histories = this.$store.getters['history/getInterviewHistoriesByDate'](date);
      console.log('按日期筛选的历史记录:', histories);
      return histories;
    },
    // 测试获取历史记录
    testGetHistory() {
      // 获取所有历史记录
      const allHistories = this.getAllHistories();

      // 获取最新历史记录
      const latestHistory = this.getLatestHistory();

      // 获取今天的历史记录
      const todayHistories = this.getHistoriesByDate();

      // 在控制台输出结果
      console.group('历史记录测试');
      console.log('所有历史记录:', allHistories);
      console.log('最新历史记录:', latestHistory);
      console.log('今天的历史记录:', todayHistories);
      console.groupEnd();

      // 也可以显示在界面上
      this.$message({
        message: `获取历史记录成功！共${allHistories.length}条记录`,
        type: 'success'
      });
    },

    // 重新分析回答
    reAnalyzeAnswer() {
      // 重置缓存和加载状态
      this.analysisCache = {
        advantage: null,
        disadvantage: null
      };
      this.hasLoadedAdvantage = false;
      this.hasLoadedDisadvantage = false;
      this.formattedAdvantageText = '';
      this.formattedDisadvantageText = '';

      // 根据当前显示的类型重新分析
      if (this.currentAnalysisType === 'advantage') {
        this.analyzeAnswerWithModel('advantage');
      } else {
        this.analyzeAnswerWithModel('disadvantage');
      }
    },
    //更新下一个问题
    ...mapActions('question', {
      updateQuestion: 'updateQuestion'
    }),
    //大模型智能分析
    toggleAnalysis() {
      this.showAnalysis = !this.showAnalysis;
      if (this.showAnalysis) {
        if (!this.hasLoadedAdvantage) {
          this.analyzeAnswerWithModel('advantage');
        } else {
          this.processAnalysisResult(this.analysisCache.advantage);
        }
      }
    },
    // 切换分析类型（优点/缺点）
    switchAnalysisType(type) {
      this.currentAnalysisType = type;

      // 如果对应类型的分析结果尚未加载，则调用大模型进行分析
      if (type === 'advantage' && !this.hasLoadedAdvantage) {
        this.analyzeAnswerWithModel('advantage');
      } else if (type === 'disadvantage' && !this.hasLoadedDisadvantage) {
        this.analyzeAnswerWithModel('disadvantage');
      }
    },
    // 处理分析错误
    handleAnalysisError(message) {
      this.modelAnalysisError = true;
      this.analysisLoading = false;
      this.modelAnalysisErrorMsg = message;
      this.$message({
        message: `大模型分析失败: ${message}`,
        type: 'error'
      });
    },
    // 调用大模型分析回答
    analyzeAnswerWithModel(type) {
      const answerText = this.formattedResult || this.globalAnswer || this.myAnswerContent;
      if (!answerText.trim()) {
        this.$message({
          message: '没有可分析的回答内容',
          type: 'warning'
        });
        return;
      }

      // 重置相关状态
      if (type === 'advantage') {
        this.formattedAdvantageText = '';
      } else if (type === 'disadvantage') {
        this.formattedDisadvantageText = '';
      }

      this.analysisLoading = true;
      this.modelAnalysisError = false;
      this.totalAnalysisRes = '';

      this.connectAnalysisModelWS(answerText, type);
    },
    // 连接大模型WebSocket
    connectAnalysisModelWS(answerText,type) {
      this.getModelDomain();

      this.getModelWebSocketUrl().then(url => {
        if ('WebSocket' in window) {
          this.analysisModelWS = new WebSocket(url);
        } else {
          this.handleAnalysisError('浏览器不支持WebSocket');
          return;
        }

        this.analysisModelWS.onopen = () => {
          this.sendAnalysisPrompt(answerText,type);
        };

        this.analysisModelWS.onmessage = e => {
          this.handleAnalysisResult(e.data,type);
        };

        this.analysisModelWS.onerror = e => {
          this.handleAnalysisError('WebSocket连接错误，请检查网络');
          console.error('大模型分析WebSocket错误:', e);
        };

        this.analysisModelWS.onclose = e => {
          this.analysisModelWS = null;
          this.analysisLoading = false;
          console.log('大模型分析WebSocket关闭');
        };
      }).catch(error => {
        this.handleAnalysisError('获取WebSocket URL失败');
        console.error('获取大模型分析WebSocket URL失败:', error);
      });
    },

    // 大模型相关方法
    getModelDomain() {
      switch (this.modelHttpUrl.pathname) {
        case "/v1.1/chat":
          this.modelDomain = "lite";
          break;
        case "/v2.1/chat":
          this.modelDomain = "generalv2";
          break;
        case "/v3.1/chat":
          this.modelDomain = "generalv3";
          break;
        case "/v3.5/chat":
          this.modelDomain = "generalv3.5";
          break;
        default:
          this.modelDomain = "generalv3.5";
      }
    },
    getModelWebSocketUrl() {
      return new Promise((resolve, reject) => {
        try {
          const host = this.modelHttpUrl.host;
          const date = new Date().toGMTString();
          const algorithm = 'hmac-sha256';
          const headers = 'host date request-line';
          const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${this.modelHttpUrl.pathname} HTTP/1.1`;
          const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.modelAPISecret);
          const signature = CryptoJS.enc.Base64.stringify(signatureSha);
          const authorizationOrigin = `api_key="${this.modelAPIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
          const authorization = btoa(authorizationOrigin);
          const url = `wss://${host}${this.modelHttpUrl.pathname}?authorization=${authorization}&date=${date}&host=${host}`;
          resolve(url);
        } catch (error) {
          reject(error);
        }
      });
    },
    connectModelWS() {
      if (this.modelLoading) return;
      this.modelLoading = true;
      this.aiAnswerContent = '生成中...';

      // 重置流式数据
      this.streamingContent = '';
      this.isStreaming = true;
      this.modelResponseBuffer = '';

      // 增加连接超时处理
      const connectTimeout = setTimeout(() => {
        if (this.modelWS && this.modelWS.readyState !== WebSocket.OPEN) {
          this.modelLoading = false;
          this.aiAnswerContent = '连接超时，请重试';
          this.isStreaming = false;
        }
      }, 15000); // 15秒超时

      this.getModelWebSocketUrl().then(url => {
        if ('WebSocket' in window) {
          this.modelWS = new WebSocket(url);
        } else {
          clearTimeout(connectTimeout);
          alert('浏览器不支持WebSocket');
          this.modelLoading = false;
          this.aiAnswerContent = '获取失败，请重试';
          this.isStreaming = false;
          return;
        }

        this.modelWS.onopen = () => {
          clearTimeout(connectTimeout);
          this.sendModelPrompt();
        };

        this.modelWS.onmessage = e => {
          this.handleModelResult(e.data);
        };

        this.modelWS.onerror = e => {
          clearTimeout(connectTimeout);
          console.error('大模型WebSocket错误:', e);
          this.modelLoading = false;
          this.aiAnswerContent = '获取失败，请重试';
          this.isStreaming = false;
        };

        this.modelWS.onclose = e => {
          clearTimeout(connectTimeout);
          console.log('大模型WebSocket关闭:', e);
          this.modelLoading = false;
          this.isStreaming = false;
        };
      }).catch(error => {
        clearTimeout(connectTimeout);
        console.error('获取大模型WebSocket URL失败:', error);
        this.modelLoading = false;
        this.aiAnswerContent = '获取失败，请重试';
        this.isStreaming = false;
      });
    },
    // 发送分析提示词
    sendAnalysisPrompt(answerText,type) {
      let promptContent = '';

      // 根据分析类型设置不同的提示词
      if (type === 'advantage') {
        promptContent = `${answerText} 假设现在正在面试，面试官问了你一个问题，你进行了回答,请仅分析这段回答的优点，要求以有序列表返回所有优点，每行一个优点，使用**包裹关键点，不需要返回缺点。`;
      }
      else if (type === 'disadvantage') {
        promptContent = `${answerText} 假设现在正在面试，面试官问了你一个问题，你进行了回答,请仅分析这段回答的缺点，并给出改进建议，要求以有序列表返回所有内容，每行一个条目，使用**包裹关键点，不需要返回优点。`;
      }
      else if (type === 'both') {
        const advantagePrompt = `${answerText} 假设现在正在面试，面试官问了你一个问题，你进行了回答,请分析这段回答的优点，要求以有序列表返回所有优点，每行一个优点，使用**包裹关键点。`;
        const disadvantagePrompt = `${answerText} 假设现在正在面试，面试官问了你一个问题，你进行了回答,请分析这段回答的缺点，并给出改进建议，要求以有序列表返回所有内容，每行一个条目，使用**包裹关键点。`;
        promptContent = `${advantagePrompt}\n\n${disadvantagePrompt}`;
      }
      // 确保提示词不为空
      if (!promptContent.trim()) {
        this.handleAnalysisError('生成的分析提示词为空');
        return;
      }

      const params = {
        "header": {
          "app_id": this.appId,
          "uid": "interview-analysis-" + Date.now()
        },
        "parameter": {
          "chat": {
            "domain": this.modelDomain,
            "temperature": 0.5,
            "max_tokens": 2048
          }
        },
        "payload": {
          "message": {
            "text": [ { "role": "user", "content": promptContent }]
          }
        }
      };

      this.analysisModelWS.send(JSON.stringify(params));
    },
    // 处理分析结果
    handleAnalysisResult(resultData,type) {
      try {
        const jsonData = JSON.parse(resultData);

        if (jsonData.payload && jsonData.payload.choices && jsonData.payload.choices.text) {
          const content = jsonData.payload.choices.text[0].content;
          this.streamingAnalysisText += content;
          console.log('【大模型分析结果】', this.streamingAnalysisText);
          this.totalAnalysisRes += content;
          console.log('【大模型原始结果】', content);
          if (jsonData.header.status === 2) {
            // 根据分析类型缓存结果
            if (type === 'advantage' || type === 'both') {
              this.analysisCache.advantage = this.totalAnalysisRes;
              console.log('优势分析',this.analysisCache.advantage)
              this.hasLoadedAdvantage = true;
            }

            if (type === 'disadvantage' || type === 'both') {
              this.analysisCache.disadvantage = this.totalAnalysisRes;
              console.log('改进建议',this.analysisCache.disadvantage)
              this.hasLoadedDisadvantage = true;
            }

            this.processAnalysisResult(''); // 处理缓存的结果
            this.totalAnalysisRes = '';
            this.streamingAnalysisText = '';
          }
        }

        if (jsonData.header.code !== 0) {
          this.handleAnalysisError(`分析失败: ${jsonData.header.code}:${jsonData.header.message}`);
          return;
        }
      } catch (error) {
        this.handleAnalysisError('解析分析结果失败');
        console.error('解析大模型分析结果失败:', error);
      }
    },
   // 处理完整分析结果
      processAnalysisResult(content) {
    // 直接使用缓存的优势和缺点数据
    var advantageText = '';
    var disadvantageText = '';

    if (this.analysisCache.advantage) {
      advantageText = this.analysisCache.advantage.trim();
      this.formattedAdvantageText = this.formatAnalysisResult(advantageText);
    }

    if (this.analysisCache.disadvantage) {
      disadvantageText = this.analysisCache.disadvantage.trim();
      this.formattedDisadvantageText = this.formatAnalysisResult(disadvantageText);
    }

    this.streamingAnalysisText = '';
    this.analysisLoading = false;
  },
    // 格式化分析结果
    formatAnalysisResult(content) {
      // 处理**包裹的内容
      const withBold = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      // 处理换行
      const withLineBreaks = withBold.replace(/\n/g, '<br>');
      // 处理有序列表
      const withLists = withLineBreaks.replace(/(\d+\.\s)/g, '<li>$1');
      // 包裹列表
      return withLists.replace(/<li>/g, '<ul><li>').replace(/<\/li>$/, '</li></ul>');
    },

    // 处理分析错误
    handleAnalysisError(message) {
      this.modelAnalysisError = true;
      this.analysisLoading = false;
      this.$message({
        message: `大模型分析失败: ${message}`,
        type: 'error'
      });
    },
    // 关闭模型WebSocket
    closeAnalysisModelWS() {
      if (this.analysisModelWS && this.analysisModelWS.readyState !== WebSocket.CLOSED) {
        this.analysisModelWS.close();
      }
      this.analysisModelWS = null;
    },
    sendModelPrompt() {
      if (!this.interviewQuestion.trim()) {
        this.modelWS.close();
        this.modelLoading = false;
        this.aiAnswerContent = '请先获取面试官问题';
        return;
      }

      const prompt = `请针对以下面试问题生成一个专业的回答建议："${this.interviewQuestion}"。
      回答应包含以下部分：
      1. 具体的回答内容
      2. 面试问该问题的具体考察点

      请使用以下格式：
      **回答内容**
      [具体的回答内容]

      **考察点分析**
      [面试问该问题的具体考察点]`;

      const params = {
        "header": {
          "app_id": this.APPID,
          "uid": "interview-assistant-" + Date.now()
        },
        "parameter": {
          "chat": {
            "domain": this.modelDomain,
            "temperature": 0.7,
            "max_tokens": 1024
          }
        },
        "payload": {
          "message": {
            "text": [
              { "role": "user", "content": "请介绍一下你自己" },
              { "role": "assistant", "content": "我是一名拥有3年软件开发经验的工程师，专注于前端开发，曾主导过多个大型项目的前端架构设计与实现..." },
              { "role": "user", "content": prompt }
            ]
          }
        }
      };

      this.modelWS.send(JSON.stringify(params));
    },

   handleModelResult(resultData) {
      try {
        // 增加日志，查看原始数据
        console.log('【原始接收数据】', resultData);

        // 处理不完整JSON数据（关键改进）
        let jsonData;
        try {
          jsonData = JSON.parse(resultData);
        } catch (parseError) {
          // 尝试拼接历史数据再解析
          this.modelResponseBuffer += resultData;
          try {
            jsonData = JSON.parse(this.modelResponseBuffer);
          } catch (concatError) {
            console.log('【不完整JSON】', this.modelResponseBuffer);
            return; // 等待更多数据
          }
        }

        if (jsonData.payload && jsonData.payload.choices && jsonData.payload.choices.text) {
          const content = jsonData.payload.choices.text[0].content;

          // 优化：处理可能的空内容
          if (!content) return;

          // 优化：正确处理流式数据前缀
          let cleanContent = content;
          if (this.isStreaming) {
            cleanContent = content.replace('生成中...', '').replace('[流式输出]', '');
          }

          // 优化：确保内容不为空
          if (cleanContent.trim() === '') return;

          // 优化：使用缓冲区更可靠地拼接内容
          this.modelResponseBuffer += cleanContent;

          // 检查是否为完整结果 (status === 2)
          if (jsonData.header.status === 2) {
            // 处理完整结果
            this.aiAnswerContent = this.formatModelResult(this.modelResponseBuffer);
            this.modelResponseBuffer = ''; // 重置缓冲区
            this.modelLoading = false;
          } else {
            // 处理流式结果
            this.aiAnswerContent = this.formatModelResult(this.modelResponseBuffer);
          }
          console.log('【大模型响应】', this.aiAnswerContent);
        }

        if (jsonData.header.code !== 0) {
          console.error(`大模型错误: ${jsonData.header.code}:${jsonData.header.message}`);
          this.aiAnswerContent = `生成失败: ${jsonData.header.message}`;
          this.modelResponseBuffer = '';
        }
      } catch (error) {
        console.error('解析大模型返回结果失败:', error);
        this.aiAnswerContent = '解析失败，请重试';
        // 不重置缓冲区，等待后续数据拼接
      }
    },

    formatModelResult(content) {
      try {
        // 优化：先处理特殊标记和换行
        let formatted = content
          .replace(/\n\n+/g, '\n\n') // 合并多余换行
          .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 处理加粗
          .replace(/\n/g, '<br>'); // 处理换行

        // 处理有序列表
        formatted = formatted.replace(/(\d+\.\s)/g, '<li>$1');

        // 处理无序列表
        formatted = formatted.replace(/\-\s/g, '<li>• $1');

        // 包裹列表标签
        formatted = formatted.replace(/<li>/g, '<ul><li>').replace(/<\/li>$/, '</li></ul>');

        // 处理标题
        formatted = formatted.replace(/^(#+)\s+/, (match, p1) => {
          const level = p1.length;
          return `<h${level+3}>${match.trim()}</h${level+3}>`;
        });

        return formatted;
      } catch (error) {
        console.error('格式化模型结果失败:', error);
        return content;
      }
    },

    closeModelWS() {
      if (this.modelWS && this.modelWS.readyState !== WebSocket.CLOSED) {
        this.modelWS.close();
      }
      this.modelWS = null;
    },

    getAiAnswer() {
      if (!this.interviewQuestion.trim()) {
        alert('请先获取面试官问题');
        return;
      }
      this.connectModelWS();
    },

    // // 原有方法
    confirmAnswer() {
      this.updateAnswer(this.recognitionResult);
      this.$message({
        message: '答案已确认',
        type: 'success'
      });
      this.tempResult = '';
    },
    ...mapActions('answer', {
      updateAnswer: 'updateAnswer'
    }),
    //生成下一个面试问题
    async generateNextQuestion() {
      this.nextQuestionLoading = true;
      this.nextQuestionContent = '生成问题中...';

      const currentQuestion = this.interviewQuestion;
      const userAnswer = this.recognitionResult || this.globalAnswer || this.myAnswerContent;

      if (!currentQuestion || !userAnswer) {
        this.nextQuestionContent = '生成失败：缺少问题或回答内容';
        this.nextQuestionLoading = false;
        return;
      }
      try {
        // 使用封装的组件生成问题
        const newQuestion = await this.$refs.questionGenerator.generateQuestion(
          currentQuestion,
          userAnswer,
          this.currentScene,
        );
        this.nextQuestionContent = newQuestion;
        this.updateQuestion(newQuestion);
        this.invokeAvatarComponent(newQuestion);
      } catch (error) {
        console.error('生成问题失败:', error);
        this.nextQuestionContent = `生成失败: ${error.message || '未知错误'}`;
      } finally {
        this.nextQuestionLoading = false;
      }
    },
    // 连接大模型WebSocket以生成下一题
    connectModelWSForNextQuestion(currentQuestion, userAnswer) {
      this.getModelDomain();

      this.getModelWebSocketUrl().then(url => {
        if ('WebSocket' in window) {
          this.modelWS = new WebSocket(url);
        } else {
          this.nextQuestionContent = '浏览器不支持WebSocket，无法生成问题';
          this.nextQuestionLoading = false;
          return;
        }

        this.modelWS.onopen = () => {
          this.sendNextQuestionPrompt(currentQuestion, userAnswer);
        };

        this.modelWS.onmessage = e => {
          this.handleNextQuestionResult(e.data);
        };

        this.modelWS.onerror = e => {
          console.error('大模型WebSocket错误:', e);
          this.nextQuestionContent = '生成失败，请重试';
          this.nextQuestionLoading = false;
        };

        this.modelWS.onclose = e => {
          console.log('大模型WebSocket关闭:', e);
          this.nextQuestionLoading = false;
        };
      }).catch(error => {
        console.error('获取大模型WebSocket URL失败:', error);
        this.nextQuestionContent = '获取失败，请重试';
        this.nextQuestionLoading = false;
      });
    },
    // 发送生成下一题的提示词
    sendNextQuestionPrompt(currentQuestion, userAnswer) {
      // 构建提示词，让大模型根据当前问题和回答生成下一个问题
      const prompt = `假设你是一个专业的面试官，现在需要根据以下信息生成下一个面试问题：

      当前问题：${currentQuestion}
      候选人回答：${userAnswer}

      生成要求：
      1. 新问题应与当前问题和候选人回答相关，深入考察候选人能力
      2. 问题应具有专业性和针对性，避免无关或重复
      3. 保持问题的开放性，让候选人有足够空间展示自己
      4. 问题应自然流畅，符合面试场景

      请直接返回生成的问题，不需要额外说明。`;

      const params = {
        "header": {
          "app_id": this.appId,
          "uid": "interview-question-generator-" + Date.now()
        },
        "parameter": {
          "chat": {
            "domain": this.modelDomain,
            "temperature": 0.7,
            "max_tokens": 1024
          }
        },
        "payload": {
          "message": {
            "text": [
              { "role": "user", "content": prompt }
            ]
          }
        }
      };

      this.modelWS.send(JSON.stringify(params));
    },
    // 处理下一题生成结果
    handleNextQuestionResult(resultData) {
      try {
        console.log('【下一题原始数据】', resultData);

        // 处理不完整JSON数据
        let jsonData;
        try {
          jsonData = JSON.parse(resultData);
        } catch (parseError) {
          // 尝试拼接历史数据
          this.modelResponseBuffer += resultData;
          try {
            jsonData = JSON.parse(this.modelResponseBuffer);
          } catch (concatError) {
            console.log('【下一题不完整JSON】', this.modelResponseBuffer);
            return;
          }
        }

        if (jsonData.payload && jsonData.payload.choices && jsonData.payload.choices.text) {
          const content = jsonData.payload.choices.text[0].content;
          // 清理可能的前缀
          let cleanContent = content.replace('生成中...', '').trim();

          if (cleanContent.trim() === '') return;

          // 优化：使用缓冲区处理下一题流式数据
          this.modelResponseBuffer += cleanContent;

          if (jsonData.header.status === 2) {
            // 完整结果
            this.nextQuestionContent = this.formatModelResult(this.modelResponseBuffer);
            console.log('大模型问题', this.nextQuestionContent);
            this.updateQuestion(this.nextQuestionContent);
            this.$nextTick(() => {
            this.invokeAvatarComponent(this.nextQuestionContent);
    });
            this.modelResponseBuffer = '';
            this.nextQuestionLoading = false;
          }
        }

        if (jsonData.header.code !== 0) {
          console.error(`大模型错误: ${jsonData.header.code}:${jsonData.header.message}`);
          this.nextQuestionContent = `生成失败: ${jsonData.header.message}`;
          this.modelResponseBuffer = '';
        }
      } catch (error) {
        console.error('解析下一题大模型返回结果失败:', error);
        this.nextQuestionContent = '解析失败，请重试';
      }
    },

    // 封装调用虚拟人组件的方法
    invokeAvatarComponent(text) {
      // 确保ai组件已初始化
      if (!this.$refs.aiComponent) {
        console.warn('AI组件未初始化，无法调用sendTextToAvatar');
        return;
      }
      if (this.$refs.aiComponent) {
        this.$refs.aiComponent.mmsendTextToAvatar(text);
      }
      const finalText = text || this.interviewQuestion;
      console.log('调用虚拟人组件，发送文本:', finalText);
    },

    initRecorder() {
      this.recorder = new RecorderManager('/dist');
      this.recorder.onStart = () => {
        this.isRecording = true;
        this.connectionStatus = 'OPEN';
      };
      this.recorder.onStop = () => {
        this.isRecording = false;
      };
      this.recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
        if (this.asrWebSocket && this.asrWebSocket.readyState === WebSocket.OPEN) {
          this.asrWebSocket.send(new Int8Array(frameBuffer));
          if (isLastFrame) this.asrWebSocket.send(JSON.stringify({ end: true }));
        }
      };
    },
    getAsrUrl() {
      const ts = Math.floor(Date.now() / 1000);
      const signa = CryptoJS.MD5(this.APPID + ts).toString();
      const signature = CryptoJS.HmacSHA1(signa, this.API_KEY).toString(CryptoJS.enc.Base64);
      return `wss://rtasr.xfyun.cn/v1/ws?appid=${this.APPID}&ts=${ts}&signa=${encodeURIComponent(signature)}`;
    },
    confirmAnswer(){
       // 将recognitionResult更新到全局状态
      this.updateAnswer(this.recognitionResult);

      // 提示用户操作成功
      this.$message({
        message: '答案已确认',
        type: 'success'
      });
      // 可选：确认后清空临时结果
      this.tempResult = '';
    },
    // 映射全局action
    ...mapActions('answer', {
      updateAnswer: 'updateAnswer'
    }),
    async handleNextQuestion() {
      // 检查大模型是否正在加载
    if (this.modelLoading || this.analysisLoading || this.nextQuestionLoading) {
      this.$message({
        message: '请等待当前内容生成完成',
        type: 'warning'
      });
      return;
    }
    this.confirmAnswer()
    if (this.answerCount >= this.maxAnswerCount) {
        // 保存所有历史记录到Vuex
        this.saveInterviewHistory();
        this.$message({
          message: '面试已完成，已保存所有回答记录',
          type: 'success'
        });
        await this.insertRecord();
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
        }
        this.insertInterviewRecord();
        // 跳转到分析页面
        this.$router.push({ path: '/basic/profile/components/try.vue' });
        this.$message({
          message: '面试已完成，正在跳转到分析页面',
          type: 'success'
        });
        return;
      }
      // 先确认当前回答
    if (this.recognitionResult || this.globalAnswer || this.myAnswerContent) {
      this.confirmAnswer();
      console.log('formattedAdvantageText:', this.formattedAdvantageText);
        console.log('formattedDisadvantageText:', this.formattedDisadvantageText);
        console.log('分析缓存', this.analysisCache);
        console.log('优势缓存', this.analysisCache.advantage);
        console.log('劣势缓存', this.analysisCache.disadvantage);
      await this.recordCurrentAnswerToHistory();
      console.log('当前回答已记录到历史');
      // 增加回答计数
      this.answerCount++;
      // 重置分析相关状态
      if(this.answerCount <this.maxAnswerCount){
        this.generateNextQuestion();
      }else{
        console.log('评价')
        this.getEvaluate();
      }
    } else {
      this.$message({
        message: '请先完成当前问题的回答',
        type: 'warning'
      });
    }
    this.recognitionResult = '';
    this.globalAnswer = '';
    this.tempResult = '';
    this.myAnswerContent = '';
    this.resetAnalysisState();
  },
async getEvaluate() {
  try {
    const currentQuestion = this.interviewQuestion;
    const userAnswer = this.recognitionResult || this.globalAnswer || this.myAnswerContent;

    if (!currentQuestion || !userAnswer) {
      this.$message.error('缺少问题或回答内容');
      return;
    }

    // 显示加载状态
    this.evaluationLoading = true;
    this.evaluationContent = '生成评价中...';

    // 调用大模型生成评价
    const evaluation = await this.generateFinalEvaluation(currentQuestion, userAnswer);

    // 更新评价内容
    this.evaluationContent = evaluation;
    this.updateQuestion(evaluation);

    // 让虚拟人说出评价
    this.invokeAvatarComponent(evaluation);

    // 保存评价结果
    this.saveEvaluationResult(evaluation);

    this.$message.success('评价生成成功');
  } catch (error) {
    console.error('生成评价失败:', error);
    this.$message.error(`评价生成失败: ${error.message || '未知错误'}`);
    this.evaluationContent = '评价生成失败，请重试';
  } finally {
    this.evaluationLoading = false;
  }
},
async generateFinalEvaluation(question, answer) {
  return new Promise((resolve, reject) => {
    const prompt = `作为专业面试官，请根据以下面试表现给出最终评价：

    问题：${question}
    回答：${answer}

     生成要求：
    1. 总结当前回答，简短总结即可
    2. 总结后说面试结束了，再见。

    示例：你今天的表现不错，面试到这里就结束了，下次见。
    请直接返回问题文本，无需额外说明。`;

    this.getModelWebSocketUrl().then(url => {
      if (!('WebSocket' in window)) {
        reject(new Error('浏览器不支持WebSocket'));
        return;
      }

      const ws = new WebSocket(url);
      let fullResponse = '';

      ws.onopen = () => {
        const params = {
          "header": {
            "app_id": this.appId,
            "uid": "final-evaluation-" + Date.now()
          },
          "parameter": {
            "chat": {
              "domain": this.modelDomain,
              "temperature": 0.5,
              "max_tokens": 1024
            }
          },
          "payload": {
            "message": {
              "text": [
                { "role": "user", "content": prompt }
              ]
            }
          }
        };
        ws.send(JSON.stringify(params));
      };

      ws.onmessage = (e) => {
        try {
          const data = JSON.parse(e.data);
          if (data.payload && data.payload.choices && data.payload.choices.text) {
            var content = data.payload.choices.text[0].content;
            fullResponse += content;

            if (data.header.status === 2) {
              resolve(this.formatEvaluation(fullResponse));
              ws.close();
            }
          }
        } catch (e) {
          console.error('解析评价结果失败:', e);
        }
      };

      ws.onerror = (e) => {
        reject(new Error('WebSocket连接错误'));
        ws.close();
      };

      ws.onclose = () => {
        if (!fullResponse) {
          reject(new Error('连接关闭未收到评价'));
        }
      };

      // 设置超时
      setTimeout(() => {
        if (ws.readyState === WebSocket.OPEN) {
          ws.close();
          reject(new Error('评价生成超时'));
        }
      }, 30000);
    }).catch(reject);
  });
},
// 格式化评价结果
formatEvaluation(text) {
  // 处理加粗标记
  let formatted = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

  // 处理标题
  formatted = formatted.replace(/【(.*?)】/g, '<h4>$1</h4>');

  // 处理列表
  formatted = formatted.replace(/(\d+\.\s)/g, '<li>$1');
  formatted = formatted.replace(/<li>/g, '<ul><li>').replace(/<\/li>/g, '</li></ul>');

  // 处理换行
  formatted = formatted.replace(/\n/g, '<br>');

  return formatted;
},

// 保存评价结果
saveEvaluationResult(evaluation) {
  // 保存到Vuex
  this.$store.commit('evaluation/setFinalEvaluation', evaluation);

  // 也可以保存到本地数据
  this.finalEvaluation = evaluation;

  // // 如果需要保存到数据库
  // this.saveEvaluationToDB(evaluation);
},
  saveInterviewHistory() {
  if (this.historyData.length > 0) {
    this.$store.dispatch('history/saveInterviewHistory', this.historyData);
    console.log('面试记录',this.historyData)
  }
},
  resetAnalysisState() {
    console.log('重置分析状态');
  // 重置分析缓存和状态
  this.analysisCache = {
    advantage: null,
    disadvantage: null
  };
  this.hasLoadedAdvantage = false;
  this.hasLoadedDisadvantage = false;
  this.streamingAnalysisText = '';
  this.formattedAdvantageText = '';
  this.formattedDisadvantageText = '';
  this.totalAnalysisRes = '';
  this.currentAnalysisType = 'advantage'; // 重置为默认显示优势分析

  // 如果分析面板是打开的，自动触发优势分析
  if (this.showAnalysis) {
    this.analyzeAnswerWithModel('advantage');
  }
},
    // 记录当前回答到历史记录
    async recordCurrentAnswerToHistory() {
      // 获取当前时间
      const now = new Date();
      const timeStr = now.toISOString().split('T')[0] + ' ' + now.toTimeString().split(':')[0] + ':' + now.toTimeString().split(':')[1];

      // 获取当前问题
      const currentQuestion = this.interviewQuestion;

      // 获取当前回答
      const currentAnswer = this.recognitionResult || this.globalAnswer || this.myAnswerContent;

      // 检查是否有回答内容
      if (!currentAnswer.trim()) {
        this.$message({
          message: '没有可评分的回答内容',
          type: 'warning'
        });
        return;
      }

      // 显示加载状态
      this.scoringLoading = true;
      this.scoringError = false;
      this.scoringErrorMessage = '';

      try {
        // 调用大模型进行评分
        console.log('formattedAdvantageText:', this.formattedAdvantageText);
        console.log('formattedDisadvantageText:', this.formattedDisadvantageText);
        console.log('分析缓存', this.analysisCache);
        console.log('优势缓存', this.analysisCache.advantage);
        console.log('劣势缓存', this.analysisCache.disadvantage);
        const score = await this.scoreAnswerWithModel(currentQuestion, currentAnswer);
        console.log('formattedAdvantageText:', this.formattedAdvantageText);
        console.log('formattedDisadvantageText:', this.formattedDisadvantageText);
        console.log('分析缓存', this.analysisCache);
        console.log('优势缓存', this.analysisCache.advantage);
        console.log('劣势缓存', this.analysisCache.disadvantage);
        // 获取分析结果
        console.log('开始获取分析结果');
        const analysisAdvantage = this.formattedAdvantageText || (this.analysisCache.advantage ? this.formatAnalysisResult(this.analysisCache.advantage) : '');
        const analysisDisadvantage = this.formattedDisadvantageText || (this.analysisCache.disadvantage ? this.formatAnalysisResult(this.analysisCache.disadvantage) : '');
        console.log('优势',analysisAdvantage)
        console.log('劣势',analysisDisadvantage)
        // 添加到历史记录
        this.historyData.unshift({
          question: currentQuestion,
          answer: currentAnswer,
          analysis: {
            advantage: analysisAdvantage,
            disadvantage: analysisDisadvantage
          },
          time: timeStr,
          score: score
        });

        // 限制历史记录数量（例如最多保留20条）
        if (this.historyData.length > 20) {
          this.historyData.pop();
        }

        this.$message({
          message: '回答已记录，评分完成',
          type: 'success'
        });
      } catch (error) {
        this.scoringError = true;
        this.scoringErrorMessage = error.message || '大模型评分失败';
        this.$message({
          message: this.scoringErrorMessage,
          type: 'error'
        });
        // 使用默认评分逻辑作为 fallback
        this.fallbackScoring(currentAnswer, analysisAdvantage, analysisDisadvantage);
      } finally {
        this.scoringLoading = false;
      }
    },
    // 调用大模型对回答进行评分
    async scoreAnswerWithModel(question, answer) {
      return new Promise((resolve, reject) => {
        // 构建评分提示词
        const prompt = `[友好评分指令]
        你是一位注重鼓励的面试官，按以下原则对回答评分：
        1. 问题：${question}
        2. 回答：${answer}
        3. 评分标准：
          - 内容相关性（25%）：是否围绕问题核心，不要求完美匹配
          - 逻辑连贯性（25%）：是否有清晰的条理（如分点、因果关系）
          - 表达流畅度（30%）：语言是否自然易懂，允许适度口语化
          - 专业补充（20%）：若有专业术语或案例加分，无则不扣分
        4. 评分策略：
          - 基础分7分（无明显错误即达标）
          - 每处优势+0.5分（如逻辑清晰、例子贴切）
          - 每处劣势-0.3分（仅扣关键缺陷，避免过度挑剔）
        5. 输出格式：返回分数（0-10）
        示例输出：8`;

        // 连接大模型WebSocket
        this.getModelWebSocketUrl().then(url => {
          if (!('WebSocket' in window)) {
            reject('浏览器不支持WebSocket，无法调用大模型评分');
            return;
          }

          const modelWS = new WebSocket(url);
          let scoreReceived = false;

          modelWS.onopen = () => {
            const params = {
              "header": {
                "app_id": this.appId,
                "uid": "interview-scoring-" + Date.now()
              },
              "parameter": {
                "chat": {
                  "domain": this.modelDomain,
                  "temperature": 0.3, // 降低温度，使评分更稳定
                  "max_tokens": 10
                }
              },
              "payload": {
                "message": {
                  "text": [
                    { "role": "user", "content": prompt }
                  ]
                }
              }
            };

            modelWS.send(JSON.stringify(params));
          };

          modelWS.onmessage = e => {
            try {
              const jsonData = JSON.parse(e.data);
              if (jsonData.payload && jsonData.payload.choices && jsonData.payload.choices.text) {
                const content = jsonData.payload.choices.text[0].content.trim();
                console.log("大模型评分返回：", content);
                // 提取数字分数
                const scoreMatch = content.match(/\d+/);
                if (scoreMatch) {
                  const score = parseInt(scoreMatch[0]);
                  if (score >= 0 && score <= 10) {
                    resolve(score);
                    scoreReceived = true;
                  } else {
                    reject(`无效分数: ${score}`);
                  }
                } else {
                  reject(`无法解析分数: ${content}`);
                }
              }
            } catch (error) {
              reject(`解析评分结果失败: ${error.message}`);
            }
          };

          modelWS.onerror = e => {
            reject(`大模型评分WebSocket错误: ${e.message}`);
          };

          modelWS.onclose = e => {
            if (!scoreReceived) {
              reject(`大模型评分连接关闭，未收到分数`);
            }
          };

          // 设置超时
          setTimeout(() => {
            if (!scoreReceived && modelWS.readyState !== WebSocket.CLOSED) {
              modelWS.close();
              reject('大模型评分超时');
            }
          }, 20000); // 20秒超时
        }).catch(error => {
          reject(`获取大模型评分WebSocket URL失败: ${error.message}`);
        });
      });
    },
    // 大模型评分失败时的 fallback 评分逻辑
    fallbackScoring(answer, analysisAdvantage, analysisDisadvantage) {
      let score =70; // 基准分70分
      console.log("【fallback评分】初始分：", score);
          // 回答长度加分（更宽松）
      const wordCount = answer.trim().split(/\s+/).length;
      if (wordCount > 80) score += 0.5; // 原100字，现80字即加分
      else if (wordCount > 50) score += 0.2; // 新增中等长度加分
      else if (wordCount < 30) score -= 0.5; // 仅极短回答扣分，原<50字扣分

      // 优势加分（每个优势+5分，原+3分）
      if (analysisAdvantage) {
        const advantageCount = (analysisAdvantage.match(/<li>/g) || []).length;
        score += advantageCount * 5; // 原*3
      }
      console.log("【fallback评分】加分后：", score);
      // 劣势扣分（每个劣势-3分，原-4分）
      if (analysisDisadvantage) {
        const disadvantageCount = (analysisDisadvantage.match(/<li>/g) || []).length;
        score -= disadvantageCount * 3; // 原*4
      }
      console.log("【fallback评分】优势加分后：", score);
      // 新增：包含关键词加分（如问题中的核心词）
      const questionKeywords = this.extractKeywords(question); // 假设提取问题关键词
      const answerKeywordCount = questionKeywords.filter(keyword =>
        answer.includes(keyword)
      ).length;
      if (answerKeywordCount > 0) {
        score += Math.min(answerKeywordCount * 2, 0.5); // 最多加5分
      }
      console.log("【fallback评分】最终分：", score);
      // 确保分数在0-100之间
      score = Math.max(5, Math.max(0, Math.min(10, score)));

      // 添加到历史记录（使用fallback分数）
      const now = new Date();
      const timeStr = now.toISOString().split('T')[0] + ' ' + now.toTimeString().split(':')[0] + ':' + now.toTimeString().split(':')[1];
      const currentQuestion = this.interviewQuestion;
      const currentAnswer = this.recognitionResult || this.globalAnswer || this.myAnswerContent;

      this.historyData.unshift({
        question: currentQuestion,
        answer: currentAnswer,
        analysis: {
          advantage: analysisAdvantage,
          disadvantage: analysisDisadvantage
        },
        time: timeStr,
        score: score
      });

      if (this.historyData.length > 20) {
        this.historyData.pop();
      }
    },

    // 查看历史记录详情
    viewHistoryDetail(item) {
      this.historyDetail = {
        question: item.question,
        answer: item.answer,
        analysis: {
          advantage: item.analysis.advantage,
          disadvantage: item.analysis.disadvantage
        },
        time: item.time,
        score: item.score
      };
      this.showHistoryModal = true;
    },

    // 关闭历史记录详情模态框
    closeHistoryModal() {
      this.showHistoryModal = false;
    },

    // 筛选历史记录
    filterHistory(type) {
      this.historyFilter = type;
    },
    initRecorder() {
      this.recorder = new RecorderManager('/dist');
      this.recorder.onStart = () => {
        this.isRecording = true;
        this.connectionStatus = 'OPEN';
      };
      this.recorder.onStop = () => {
        this.isRecording = false;
      };
      this.recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
        if (this.asrWebSocket && this.asrWebSocket.readyState === WebSocket.OPEN) {
          this.asrWebSocket.send(new Int8Array(frameBuffer));
          if (isLastFrame) this.asrWebSocket.send(JSON.stringify({ end: true }));
        }
      };
    },
    getAsrUrl() {
      const ts = Math.floor(Date.now() / 1000);
      const signa = CryptoJS.MD5(this.APPID + ts).toString();
      const signature = CryptoJS.HmacSHA1(signa, this.API_KEY).toString(CryptoJS.enc.Base64);
      return `wss://rtasr.xfyun.cn/v1/ws?appid=${this.APPID}&ts=${ts}&signa=${encodeURIComponent(signature)}`;
    },
    connect() {
      this.isLoading = true;
      this.connectionStatus = 'CONNECTING';
      this.recognitionResult = '';
      this.tempResult = '';
      this.startScoreTimer();

      // 建立ASR连接
      this.asrWebSocket = new WebSocket(this.getAsrUrl());
      this.asrWebSocket.binaryType = 'arraybuffer';

      this.asrWebSocket.onopen = () => {
        this.isLoading = false;
        this.recorder.start({ sampleRate: 16000, frameSize: 1280 });
      };
      this.asrWebSocket.onmessage = e => this.handleAsrMessage(e.data);
      this.asrWebSocket.onerror = () => {
        this.recognitionResult += `<p class="error">ASR 连接错误，请重试</p>`;
        this.disconnect();
      };
      this.asrWebSocket.onclose = () => this.disconnect();
    },
    disconnect() {
      this.isRecording = false;
      this.isLoading = false;
      this.connectionStatus = 'CLOSED';
      this.recorder.stop();
      if (this.asrWebSocket) this.asrWebSocket.close();
      this.asrWebSocket = null;
      if (this.scoreTimer) {
        clearInterval(this.scoreTimer);
        this.scoreTimer = null;
      };
    },
    handleAsrMessage(msg) {
    console.log("收到ASR消息：", msg);
    const j = JSON.parse(msg);
    if (j.action === 'result') {
      const dt = JSON.parse(j.data);
      console.log("ASR解析数据：", dt);
      console.log("dt.cn.st.type =", dt.cn.st.type);
      let text = '';
      dt.cn.st.rt.forEach(rt =>
        rt.ws.forEach(ws =>
          ws.cw.forEach(c => (text += c.w))
        )
      );
      if (dt.cn.st.type == 0) {
        this.recognitionResult += text;
        this.tempResult = '';
        console.log("发送文本给分析服务:", this.recognitionResult);
        this.sendTextForAnalysis(this.recognitionResult);
      } else {
        this.tempResult = text;
      }
    }
    },
    startScoreTimer() {
      this.scoreTimer = setInterval(() => {
        if (
          this.analysisResult &&
          this.analysisResult.sentiment &&
          this.analysisResult.sentiment.length > 0
        ) {
          const score = this.analysisResult.sentiment[0].score;
          const timestamp = (this.scoreHistory.length + 1).toString();
          this.scoreHistory.push({ time: timestamp, score: score * 10 });

          this.updateScoreChart();
        }
      }, 1000); // 每秒记录一次
    },
    // 分析WebSocket相关
    initAnalysisWebSocket() {
      this.analysisWebSocket = new WebSocket("ws://121.43.49.125:8000/ws/asr_emotion_logic");
      this.analysisWebSocket.onopen = () => {
        this.analysisWSConnected = true;
        console.log("分析 WebSocket 已连接");
      };
      this.analysisWebSocket.onmessage = e => {
        try {
          this.analysisResult = JSON.parse(e.data);
          console.log("分析结果：", this.analysisResult);
        } catch {
          this.analysisResult = {
            text: '',
            sentiment: '解析失败',
            logic: { similarity: 0, flag: false, message: '返回异常' },
          };
        }
      };
      this.analysisWebSocket.onerror = () => {
        this.analysisResult = {
          text: '',
          sentiment: '分析服务失败',
          logic: { similarity: 0, flag: false, message: '' },
        };
      };
      this.analysisWebSocket.onclose = () => {
        this.analysisWSConnected = false;
        console.log("分析 WebSocket 已关闭");
      };
    },

    sendTextForAnalysis(text) {
      if (this.analysisWSConnected && this.analysisWebSocket.readyState === WebSocket.OPEN) {
        this.analysisWebSocket.send(JSON.stringify({ text }));
        console.log("发送文本给分析服务:", text);
      } else {
        console.warn("分析 WebSocket 未连接，无法发送文本");
      }
    },

    cleanupAnalysisWS() {
      if (this.analysisWebSocket && this.analysisWebSocket.readyState === WebSocket.OPEN) {
        this.analysisWebSocket.close();
      }
      this.analysisWebSocket = null;
      this.analysisWSConnected = false;
    },

    toggleRecording() {
      this.resetAnalysisState();
      if (this.connectionStatus === 'CLOSED') {
        this.connect();
        this.isRecording = true;
      } else {
        this.disconnect();
        this.isRecording = false;
      }
    },
    updateScoreChart() {
      if (!this.scoreChartInstance) {
        this.scoreChartInstance = echarts.init(this.$refs.scoreChart);
      }

      const times = this.scoreHistory.map(item => item.time);
      const scores = this.scoreHistory.map(item => item.score);

      const gradientColor = {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
          { offset: 0, color: '#ffe082' },
          { offset: 1, color: '#fffde7' }
        ]
      };

      this.scoreChartInstance.setOption({
        grid: { left: 36, right: 24, top: 24, bottom: 24 },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#fff',
          borderColor: '#eee',
          textStyle: { color: '#444' },
          formatter: (params) => {
            const p = params[0];
            return `时间：${p.axisValue}<br>得分：<b style="color:${p.data >= 8 ? '#4caf50' : (p.data < 6 ? '#f44336' : '#ff9800')}">${(p.data).toFixed(1)}</b>`;
          },
          extraCssText: 'box-shadow:0 2px 8px rgba(200,180,120,0.08);'
        },
        xAxis: {
          type: 'category',
          data: times,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13,
            margin: 8
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 10,
          interval: 2,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13
          },
          splitLine: { lineStyle: { color: '#f5f5f5', width: 1 } }
        },
        dataZoom: [
          {
            type: 'slider',
            show: scores.length > 8,
            xAxisIndex: 0,
            start: scores.length > 8 ? ((scores.length - 8) / scores.length) * 100 : 0,
            end: 100,
            height: 8,
            bottom: 0
          }
        ],
        series: [
          {
            data: scores,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#ffb347',
              width: 2
            },
            itemStyle: {
              color: (params) => {
                if (params.value >= 8) return '#4caf50'; // 高分绿色
                if (params.value < 6) return '#f44336'; // 低分红
                return '#ffb347'; // 正常橙
              },
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: gradientColor
            },
            label: {
              show: true,
              color: '#555',
              fontSize: 12,
              formatter: (v) => (v.value).toFixed(1),
              position: 'top'
            },
            markLine: {
              silent: true,
              data: [
                { yAxis: 8, lineStyle: { color: '#4caf50', type: 'dashed' }, label: { show: true, formatter: '' } },
                { yAxis: 5, lineStyle: { color: '#f44336', type: 'dashed' }, label: { show: true, formatter: '' } }
              ]
            }
          }
        ]
      });
    },
    toggleRun() {
      if (this.running) {
        this.stopRecognition()
      } else {
        this.startRecognition()
      }
    },
    async startRecognition() {
      this.running = true
      this.duration = 0
      this.emotionHistory = []

      await this.startCamera()
      this.startWebsocket()

      this.timer = setInterval(() => {
        this.duration++
        if (this.duration % 2 === 0) {
          this.emotionHistory.push({
            time: `${Math.floor(this.duration / 60)}:${String(this.duration % 60).padStart(2, '0')}`,
            emotion: this.currentEmotion || 'unknown',
          })
        }
        this.$nextTick(this.drawChart)
      }, 1000)
    },
    stopRecognition() {
      this.running = false
      clearInterval(this.timer)

      if (this.socket) this.socket.close()
      if (this.videoStream) {
        this.videoStream.getTracks().forEach(track => track.stop())
      }
    },
    async startCamera() {
      this.videoStream = await navigator.mediaDevices.getUserMedia({ video: true })
      this.$refs.video.srcObject = this.videoStream
    },
    startWebsocket() {
      this.socket = new WebSocket('ws://121.43.49.125:3000/ws/emotion')

      this.socket.onopen = () => this.captureFrames()
      this.socket.onmessage = (event) => {
        const data = JSON.parse(event.data)
        if (Array.isArray(data.result) && data.result.length > 0) {
          // 获取第一个检测结果（假设主要分析第一个检测到的人脸）
          const firstResult = data.result[0]
          this.currentEmotion = this.translateEmotion(firstResult.label)
        }
      }
    },
    captureFrames() {
      const video = this.$refs.video
      const canvas = document.createElement('canvas')
      canvas.width = 300
      canvas.height = 300
      const ctx = canvas.getContext('2d')

      const sendFrame = () => {
        if (!this.running || this.socket.readyState !== WebSocket.OPEN) return
        ctx.drawImage(video, 0, 0, 300, 300)
        const frameBase64 = canvas.toDataURL('image/jpeg').split(',')[1]
        this.socket.send(JSON.stringify({ frame : frameBase64 }))
        setTimeout(sendFrame, 200)
      }

      sendFrame()
    },
    drawChart() {
      // 检查 DOM 和数据
      if (!this.$refs.chart) {
        console.warn('图表容器未准备好或数据为空');
        return;
      }
      try{

        const emotionEmojiMap = {
          '严肃': '😠',
          '开心': '😄',
          '悲伤': '😢',
          '中性': '😐',
          '厌恶': '🤢',
          '惊讶': '😲',
          '恐惧': '😨',
          '未知': '❓'
        }
          // 只保留表情变化的节点
          let filtered = [];
          let lastEmotion = null;
          this.emotionHistory.forEach(item => {
            if (item.emotion !== lastEmotion) {
              filtered.push(item);
              lastEmotion = item.emotion;
            }
          });
          const times = filtered.length ? filtered.map(item => item.time) : ['0:00'];
          const emotions = filtered.length ? filtered.map(item => item.emotion) : ['未知'];
          // 计算默认显示最后8个
          const total = times.length;
          const showCount = 8;
          const start = total > showCount ? ((total - showCount) / total) * 100 : 0;
          const end = 100;

          this.chart = echarts.init(this.$refs.chart);
          this.chart.setOption({
            tooltip: {
              trigger: 'axis',
              formatter: (params) => {
                const emotion = params[0].data;
                return `时间：${params[0].axisValue}<br/>表情：${emotion} ${emotionEmojiMap[emotion] || ''}`;
              },
            },
            dataZoom: [
              {
                type: 'slider',
                show: true,
                xAxisIndex: 0,
                start: start,
                end: end,
                height: 8,
                bottom: 0
              }
            ],
          xAxis: {
            name:'时间',
            type: 'category',
            data: times,
            nameGap:5,
          },
          yAxis: {
            name:'表情',
            type: 'category',
            data: [...new Set(emotions)],
          },
          series: [
            {
              name: '表情',
              type: 'line',
              data: emotions,
              label: {
                show: true,
                formatter: (params) => {
                  const e = params.value
                  return `${emotionEmojiMap[e] || ''} ${e}`
                },
              },
              symbolSize:4,
            },
          ],
        })
      } catch (error) {
          console.error('绘制图表失败:', error);
        }
    },
    translateEmotion(en) {
      const map = {
        angry: '严肃',
        happy: '开心',
        sad: '悲伤',
        neutral: '中性',
        disgust: '厌恶',
        surprised: '惊讶',
        scared: '恐惧',
      }
      return map[en] || en
    },
    //结束插入聊天记录到数据库
    insertRecord() {
      const latest=this.$store.getters['history/getLatestInterviewHistory'];
      console.log('最新历史记录：',latest);
      this.recordDataForm.record=JSON.stringify(latest.records);
      this.recordDataForm.inid=JSON.stringify(latest.id);
      localStorage.setItem('id',this.recordDataForm.inid);
      this.recordDataForm.voice=JSON.stringify(this.scoreHistory);
      this.recordDataForm.vedio=JSON.stringify(this.emotionHistory);
            request({
                url: '/api/example/Whu_record',
                method:'post',
                data:this.recordDataForm,
            })
            console.log('插入记录成功')
    },
    //插入面试记录到数据库
    insertInterviewRecord(){
      const sceneOptions = [
            { label: '技术面试', value: 'technical' },
            { label: '压力面试', value: 'pressure' },
            { label: '项目经验面试', value: 'project' },
            { label: '案例面试', value: 'case' },
            { label: '行为面试', value: 'behavioral' },
            { label: '薪资谈判', value: 'salary' },
            { label: '默认场景', value: 'default' }
       ];
      const latest=this.$store.getters['history/getLatestInterviewHistory'];
      this.interviewRecordForm.inid=JSON.stringify(latest.id);
      console.log('面试场景',this.selectedScenes)
      console.log('面试官风格',this.interviewerFromStore.name)
      const sceneLabels = this.selectedScenes.map(val => {
      const found = sceneOptions.find(item => item.value === val);
      return found ? found.label : val;
      });
      this.interviewRecordForm.scene = JSON.stringify(sceneLabels);
      this.interviewRecordForm.style=JSON.stringify(this.interviewerFromStore.name);
      const roles = roleOptions[this.getTechField] || [];
      const found = roles.find(item => item.value === this.getPosition);
      console.log('职位',found.label)
      this.interviewRecordForm.type=JSON.stringify(found.label);
      this.interviewRecordForm.time=JSON.stringify(this.dura);
      this.interviewRecordForm.intype=JSON.stringify('0');
      request({
                url: '/api/system/Whu_interviewrecord',
                method:'post',
                data:this.interviewRecordForm,
            })
            console.log('插入聊天记录成功')
    }
  }
}
</script>

<style scoped>

.reanalyze-btn {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background-color:#f5f5f5;
  color: rgb(13, 1, 1);
}

.reanalyze-btn:hover {
  opacity: 0.9;
}

.interview-analysis-container {
  padding-top: 1%;
  display: flex;
  gap: 20px;
  height: 88vh;
  overflow: hidden;
  background-color: rgb(254, 252, 238);
}

.left-section {
  flex: 0 0 400px;
  min-width: 400px;
  height: 75vh;
  display: flex;
  flex-direction: column;
  margin-left: 10px;

  background-image: url('../../../../assets/images/interview_bg.png');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;

  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}

.ai-wrapper {
  width: 100% !important;
  height: auto !important;
  position: relative !important;
}

.middle-section {
  flex: 1;
  min-width: 600px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.right-section{
  flex: 0 0 330px;
  min-width:330px;
  height: 75vh;
  display: flex;
  flex-direction: column;
  margin-right: 10px;
  background-color:#ffffff;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}


.right-section.history-section {
  flex: 0 0 330px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  position: relative;
}

.video-wrap {
  width: 100%;
  height: 35%;
}

.qa-interact {
  padding: 5px;
  display: flex;
  flex-direction: column;
}

.question-box{
  display: flex;
  flex-direction: column;
}

.answer-box,
.ai-answer {
  width: 100%; /* 让两个区域宽度占满父容器 */
}

.question-label,
.answer-label {
  font-weight: bold;
  margin-bottom: 5px;
  color: #8b5a2b;
}

.question-content1,
.answer-content1 {
  margin: 0;
  line-height: 1.4;
  color: #555;
}

.btn-group {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
}

.btn-group1 {
  display: flex;
  gap: 10px;
  margin-left: 10%;
  margin-top: 10px;
}

.analysis-btn,
.next-btn {
  padding: 10px 0px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  color: #fff;
  width: 120px;
}

.analysis-btn1,
.next-btn1 {
  padding: 10px 10px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  color: #fff;
  width: 120px;
}

.next-btn1:disabled {
  background-color: #d3d3d3; /* 灰色背景 */
  color: #666; /* 深灰色文字 */
  cursor: not-allowed; /* 禁用光标 */
  opacity: 0.7; /* 透明度降低 */
  box-shadow: none; /* 移除阴影 */
  transform: none; /* 重置变换 */
}

.analysis-btn:hover,
.next-btn:hover {
  opacity: 0.9;
}

/* 中间区域样式优化 */
.top-analysis {
  display: flex;
  gap: 10px;
}

.analysis-card {
  flex: 1.2;
  min-width: 0;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.emotion-chart {
  margin-bottom: 0px;
}

.wave {
  border-radius: 4px;
}

.emotion-score {
  margin-bottom: 5px;
  color: #555;
}

.expression-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.expression-icon {
  font-size: 40px;
  color: #8b5a2b;
}

.expression-text p {
  margin: 0;
  line-height: 1.4;
  color: #555;
}

.answer-comparison-card {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.answer-title-group {
  display: flex;
  justify-content: space-between;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.my-answer-title,
.ai-answer-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.answer-content-group {
  display: flex;
  flex-direction: column;
}

.answer-panel {
  flex: 1;
  padding: 10px;
  border-radius: 8px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 190px;
  margin-bottom: 5px;
}
.no-answer, .default-answer {
  text-align: center;
  color: #999;
  padding: 30px 10px;
  font-size: 14px;
  width: 100%;
}

.my-answer {
  background-color: #f9f9f9;
  border: 1px solid #eaeaea;
}
.no-answer-icon {
  font-size: 40px;
  margin-bottom: 10px;
  color: #ddd;
}

.ai-answer {
  background-color: #f0f7ff;
  border: 1px solid #d1e3fc;
}

.no-answer-text {
  line-height: 1.4;
}

.question-content {
  margin: 0;
  line-height: 1.4;
  color: #555;
  max-height: 350; /* 设置最大高度 */
  overflow-y: auto; /* 垂直方向滚动 */
  padding: 5px; /* 增加内边距避免内容贴边 */
  background-color: #f9f9f9; /* 背景色 */
}

.answer-content2 {
  margin: 0;
  line-height: 1.4;
  color: #555;
  height: 80px;
  max-height: 100px; /* 设置最大高度 */
  overflow-y: auto; /* 垂直方向滚动 */
  padding: 5px; /* 增加内边距避免内容贴边 */
  border: 1px solid #eaeaea; /* 添加边框 */
  border-radius: 8px; /* 圆角 */
  background-color: #f9f9f9; /* 背景色 */
}

.right-section.history-section {
  flex: 0 0 300px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  position: relative;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 10px 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.history-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.history-filter select {
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
}

.history-scroll-container {
  max-height: 340px;
  border-radius: 8px;
  background-color: #fff;
  border: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.history-list {
  padding: 10px;
  max-height:340px;
  overflow-y: auto;
}

.history-item {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  margin-bottom: 10px;
}
/* 无回答记录样式 */
.no-history-record {
  height: 340px;
  padding: 30px 10px;
  color: #999;
  font-size: 14px;
  text-align: center;
  border-top: 1px solid #eee;
}
.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.history-question {
  margin-bottom: 10px;
}

.no-record-icon {
  margin-top: 30%;
  font-size: 40px;
  margin-bottom: 10px;
  color: #ddd;
}

.no-record-text {
   padding: 10px 0;
}

.history-q-title {
  font-weight: bold;
  color: #8b5a2b;
  margin-bottom: 5px;
}

.history-q-content {
  margin: 0;
  line-height: 1.4;
  color: #555;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #777;
}

.history-time, .history-score {
  margin: 0;
}

.history-score {
  color: #333;
  font-weight: bold;
}

img {
  width: 300px;
  border: 1px solid #ccc;
}

/* 分析模态框样式 */
.analysis-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
}
.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.analysis-panel {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 1200px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eaecef;
}

.panel-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.analysis-content {
  display: flex;
  padding: 20px;
}

.analysis-left {
  flex: 3;
  padding-right: 20px;
}

.analysis-right {
  flex: 2;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaecef;
}

.answer-display {
  background-color: #f9f9f9;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 15px;
  min-height: 200px;
  line-height: 1.6;
  overflow-y: auto;
}

.advantage-list, .disadvantage-list {
  margin-bottom: 20px;
}

.advantage-list ul, .disadvantage-list ul {
  padding-left: 20px;
}

.advantage-list li {
  color: #36a855;
  margin-bottom: 8px;
}

.disadvantage-list li {
  color: #f56c6c;
  margin-bottom: 8px;
}
.model-analysis-result {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  margin-top: 10px;
}

.result-container {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
  min-height: 80px;
  text-align: left;
  white-space: pre-wrap;
  overflow-y: auto;
  max-height: 200px;
  word-break: break-all;
}

.analysis-loading {
  text-align: center;
  padding: 20px 0;
  color: #999;
}

.analysis-error {
  color: #f56c6c;
  padding: 10px 0;
}
/* 样式部分保持不变，可根据需要添加新样式 */
  .analysis-type-toggle {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
  }

  .analysis-type-btn {
    padding: 8px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    background-color: #f5f5f5;
    transition: all 0.3s;
  }

  .analysis-type-btn.active {
    background-color: #8b5a2b;
    color: white;
    border-color: #8b5a2b;
  }

  .analysis-type-toggle {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
  }

  .analysis-type-btn {
    padding: 8px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    background-color: #f5f5f5;
    transition: all 0.3s;
  }

  .analysis-type-btn.active {
    background-color: #8b5a2b;
    color: white;
    border-color: #8b5a2b;
  }

  .history-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
.history-detail-panel {
  position: relative;
  background-color: white;
  border-radius: 8px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
.detail-content {
  padding: 10px;
}
.detail-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: #f9f9f9;
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  padding-bottom: 5px;
  border-bottom: 1px solid #ddd;
}

.subsection-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0 10px;
  color: #555;
}

.question-display, .answer-display, .analysis-display, .info-display {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #555;
}

.info-label {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}

.no-analysis {
  color: #999;
  font-style: italic;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.history-filter {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.filter-btn {
  padding: 1px 4px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.filter-btn:hover {
  background-color: #e0e0e0;
}

.filter-btn.active {
  background-color: #4a90e2;
  color: white;
  border-color: #4a90e2;
}

.history-item {
  padding: 15px;
  margin-bottom: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.history-item:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.high-score {
  border-color: #a1f3a4;
}

.low-score {
  border-color: #fdbd4e;
}

.history-q-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.history-q-content {
  margin-bottom: 10px;
  color: #555;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #777;
}

.history-time {
  font-style: italic;
}

.history-score {
  font-weight: bold;
}
.analysis-btn:disabled,
.next-btn:disabled {
  background-color: #d3d3d3; /* 灰色背景 */
  color: #666;              /* 深灰色文字 */
  cursor: not-allowed;      /* 禁用光标 */
  opacity: 0.7;             /* 透明度降低 */
  box-shadow: none;         /* 移除阴影 */
  transform: none;          /* 重置变换 */
}
.camera-area {
  position: relative;
  width: 300px;
  height: 200px;
  background: #c3c2c2;
  border-radius: 2px;
  overflow: hidden;
}
.camera-toggle-btn {
  position: absolute;
  left: 50%;
  bottom: 12px;
  transform: translateX(-50%);
  background: #fff;
  border: none;
  padding: 7px;
  border-radius: 20px;
  color: #5b5b5b;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
}
.camera-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 2px;
  background: #c3c2c2;
}
/* 未开启摄像头时按钮一直显示 */
.camera-toggle-btn.always-show {
  opacity: 1;
  pointer-events: auto;
}

/* 开启摄像头时，鼠标悬浮才显示按钮 */
.camera-area:hover .camera-toggle-btn {
  opacity: 1;
  pointer-events: auto;
}

.white-bar {
  display: flex;
  align-items: center;
  display: flex;
  flex-direction: row;
  gap: 10px;
  padding: 10px;
  color: #3a1700;
  background-color: #ffffff;
}

.timer {
  font-size: 16px;
  margin-right: 10px;
}
.flex-spacer {
  flex-grow: 1;
}

.end-button {
  background-color: rgb(245, 231, 231);
  color: rgb(244, 109, 109);
  border: none;
  border-radius:6px;
  padding: 8px 16px;
  cursor: pointer;
}
.answer-scroll-container {
  max-height: 200px;
  overflow-y: auto;
}
.beautify-btn {
  padding: 10px 10px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 10px;
}

/* 按钮颜色 */
.next-btn {
  background-color: #01272e;
  color: white;
}

.analysis-btn1 {
  background-color: #371b01;
  color: white;
}

.analysis-btn {
  background-color: #1c001a;
  color: white;
}

.next-btn1 {
  background-color: #003609;
  color: white;
}

/* 悬停效果 */
.beautify-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

/* 禁用状态样式 */
.beautify-btn:disabled {
  background-color: #ccc;
  color: #666;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

</style>
